package com.cory.boot.utils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.core.env.Environment;
import com.cory.boot.sys.entity.SysDictValue;
import com.cory.boot.sys.entity.SysParam;
import com.cory.boot.sys.mapper.SysDictValueMapper;
import com.cory.boot.sys.mapper.SysParamMapper;
import com.cory.utils.lang.StringUtils;
import com.google.common.collect.Maps;

public class CommonData {
    
    public static String getEnvConfig(String key) {
        return SpringUtils.getBean(Environment.class).getProperty(key);
    }

	public static String getStrParam(String paramName) {
		SysParamMapper mapper = SpringUtils.getBean(SysParamMapper.class);
		SysParam param = mapper.selectById(paramName);
		return param != null ? param.getParamValue() : null;
	}

	public static Map<String,String> getDictMap(String dictCode) {
		SysDictValueMapper mapper = SpringUtils.getBean(SysDictValueMapper.class);
		List<SysDictValue> list = mapper.selectByCode(dictCode);
		list.removeIf(i -> i.getState() != 1);
		return null == list ? Maps.newHashMap() : list.stream().collect(Collectors.toMap(SysDictValue::getDictKey, SysDictValue::getDictValue));
	}

	public static String getDictValue(String dictCode, String dictKey) {
		if(StringUtils.isEmpty(dictKey)) {
			return "";
		}
		SysDictValueMapper mapper = SpringUtils.getBean(SysDictValueMapper.class);
        List<SysDictValue> list = mapper.selectByCode(dictCode);
        Map<String,String> map = null == list ? Maps.newHashMap() : list.stream().collect(Collectors.toMap(SysDictValue::getDictKey, SysDictValue::getDictValue));
		return map.get(dictKey);
    }

	public static List<SysDictValue> getDictList(String dictCode) {
		SysDictValueMapper mapper = SpringUtils.getBean(SysDictValueMapper.class);
		List<SysDictValue> list = mapper.selectByCode(dictCode);
		return list;
	}

	/**
	 * 根据字典Keys获取Value值，已","隔开
	 * @param dictCode
	 * @param dictKeys
	 * @return
	 */
	public static String getDictValues(String dictCode,String dictKeys) {
		if(StringUtils.isNotBlank(dictKeys)) {
			List<String> dictKeyList = Arrays.asList(dictKeys.split(","));
			SysDictValueMapper mapper = SpringUtils.getBean(SysDictValueMapper.class);
			return mapper.selectValueConcatByKeys(dictCode,dictKeyList);
		}
		return "";
	}

	/**
	 * 根据字典Values获取Key值，已","隔开
	 * @param dictCode
	 * @param dictValues
	 * @return
	 */
	public static String getDictKeys(String dictCode,String dictValues) {
		if(StringUtils.isNotBlank(dictValues)) {
			List<String> dictValuesList = Arrays.asList(dictValues.split("\\|"));
			SysDictValueMapper mapper = SpringUtils.getBean(SysDictValueMapper.class);
			return mapper.selectKeyConcatByValues(dictCode,dictValuesList);
		}
		return "";
	}

}
